<template>
  <a-spin :spinning="tableLoading" size="large">
    <a-card class="app" :hoverable="true">
      <a-row justify="space-between" style="margin-bottom: 20px">
        <a-col :span="12">
          <a-space :size="20">
            <h3 style="display: inline">电键：{{ data.form.docEntry }}</h3>
            <h3 style="display: inline">名称：{{ data.form.objName }}</h3>
            <h3 style="display: inline">状态：{{ data.form.docStatus }}</h3>
          </a-space>
        </a-col>
        <a-col :span="12">
          <a-row justify="end">
            <a-button-group>
              <a-button @click="back()" value="1"> 返 回</a-button>
              <a-button @click="save()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || !data.form.edit)">
                保 存
              </a-button>
              <a-button @click="edit()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || data.form.edit)">
                编 辑
              </a-button>
              <a-button @click="del()" v-if="!(data.form.edit || data.form.docStatus === 'L')" value="5"> 删 除</a-button>
              <a-dropdown arrow v-if="!(data.form.edit || data.form.docStatus === 'L')">
                <a-button>更多操作</a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a" :disabled="!(data.form.docStatus !== 'C')">关闭</a-menu-item>
                    <a-menu-item key="b" :disabled="!(data.form.docStatus === 'C')">打开</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="refresh" value="7"> 刷 新</a-button>
            </a-button-group>
          </a-row>
        </a-col>
      </a-row>

      <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 5 }">
        <a-row class="smart-query-form-row">
          <a-col :span="6">
            <a-form-item label="考场名称" name="romName">
              <a-input v-if="data.form.edit" v-model:value="data.form.romName" />
              <span v-else class="a-underline"> {{ data.form.romName }}</span>
            </a-form-item>
            <a-form-item label="试卷" name="paperId">
              <a-select key="docEntry" v-if="data.form.edit" v-model:value="data.form.paperId" @change="change">
                <a-select-option v-for="it in data.options.paper" :key="it.paperName" :value="it.docEntry">{{ it.paperName }}</a-select-option>
              </a-select>
              <span v-else class="a-underline">{{ data.form.paperName }}</span>
            </a-form-item>

            <a-form-item label="禁止提前交卷" name="fobExam">
              <a-radio-group v-if="data.form.edit" v-model:value="data.form.fobExam">
                <a-radio value="A">开启</a-radio>
                <a-radio value="B">关闭</a-radio>
              </a-radio-group>
              <span v-else class="a-underline">
                <span v-if="data.form.fobExam === 'A'">开启</span>
                <span v-if="data.form.fobExam === 'B'">关闭</span>
              </span>
            </a-form-item>

            <a-form-item label="考试次数" name="examNum">
              <a-input-number
                style="width: 80%"
                :formatter="(value) => `${value} &nbsp;次`"
                v-if="data.form.edit"
                v-model:value="data.form.examNum"
                :min="1"
                :max="200"
              />
              <span v-else class="a-underline">{{ data.form.examNum }}</span>
            </a-form-item>
            <a-form-item label="封面" name="thumbnail">
              <a-image :width="100" :height="100" :src="data.form.thumbnail" />
              <a-input-group compact v-if="data.form.edit">
                <a-input v-model:value="data.form.thumbnail" style="width: calc(100% - 100px)" />
                <a-button type="primary" @click="data.uploadModalFlag = true">上传</a-button>
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="显示成绩类型：" name="showScore">
              <a-radio-group v-if="data.form.edit" v-model:value="data.form.showScore">
                <a-radio value="A">不显示</a-radio>
                <a-radio value="B">显示成绩</a-radio>
                <a-radio value="C">显示成绩+试卷</a-radio>
              </a-radio-group>
              <span v-else class="a-underline">
                <span v-if="data.form.showScore === 'A'">不显示</span>
                <span v-if="data.form.showScore === 'B'">显示成绩</span>
                <span v-if="data.form.showScore === 'C'">显示成绩+试卷</span>
              </span>
            </a-form-item>

            <a-form-item label="开始日期" name="beginDate">
              <a-date-picker v-if="data.form.edit" show-time v-model:value="data.form.beginDate" valueFormat="YYYY-MM-DD HH:mm:ss" />
              <span v-else class="a-underline">{{ data.form.beginDate }}</span>
            </a-form-item>
            <a-form-item label="结束日期" name="endDate">
              <a-date-picker v-if="data.form.edit" show-time v-model:value="data.form.endDate" valueFormat="YYYY-MM-DD HH:mm:ss" />
              <span v-else class="a-underline">{{ data.form.endDate }}</span>
            </a-form-item>

            <a-form-item label="备注">
              <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
              <span v-else class="a-underline">{{ data.form.remark }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="制单">
              <span class="a-underline">{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span class="a-underline">{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-row>
        <a-tabs v-model:activeKey="data.activeKey" style="width: 100%">
          <a-tab-pane key="1" tab="人员">
            <a-row>
              <a-button-group>

                <a-popconfirm v-if="data.form.docEntry" title="确认全部开通吗?" ok-text="确认" cancel-text="取消" @confirm="linebAllOpen">
                  <a-button type="link">
                    <template #icon>
                      <ImportOutlined />
                    </template>
                    全部开通
                  </a-button>
                </a-popconfirm>


                <a-popconfirm
                  v-if="data.form.docEntry "
                  title="确认全部取消开通吗?"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="linebAllDel"
                >
                  <a-button type="link">
                    <template #icon>
                      <ImportOutlined />
                    </template>
                    取消开通
                  </a-button>
                </a-popconfirm>

                <a-button type="link" @click="lineaAdd" v-if="data.form.docEntry ">
                  <template #icon>
                    <ImportOutlined />
                  </template>
                  选择开通
                </a-button>
              </a-button-group>
            </a-row>

            <a-table
              row-key="lineNum"

              :columns="columnsa"
              :data-source="data.form.lista"
              :scroll="{ y: 450, x: 1500 }"
              :pagination="{
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 20,
                pageSizeOptions: ['20', '50', '100', '200'],
              }"
            >
              <template #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                <div style="padding: 8px">
                  <a-input
                    ref="searchInput"
                    :value="selectedKeys[0]"
                    style="width: 188px; margin-bottom: 8px; display: block"
                    @change="(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                    @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
                  />

                  <a-button-group>
                    <a-button type="primary" @click="handleSearch(selectedKeys, confirm, column.dataIndex)"> 搜索</a-button>
                    <a-button @click="handleReset(clearFilters)">重置</a-button>
                  </a-button-group>
                </div>
              </template>

              <template #bodyCell="{ text, record, column }">
                <template v-if="record.edit && column.dataIndex === 'romName'">
                  <a-input v-model:value="record.romName" />
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <a-button
                    :disabled="data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved"
                    @click="lineaEdit(record)"
                    type="link"
                    danger
                  >
                    <template #icon>
                      <RedoOutlined />
                    </template>
                  </a-button>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="明细">
            <a-table
              row-key="lineNum"

              :columns="columnsb"
              :data-source="data.form.listb"
              summary-fixed
              :scroll="{ y: 450, x: 1500 }"
              :pagination="{
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 20,
                pageSizeOptions: ['20', '50', '100', '200'],
              }"
            >
              <template #bodyCell="{ text, record, column }">
                <template v-if="column.dataIndex === 'corrent'">
                  <a-tag v-if="record.corrent">正确</a-tag>
                  <a-tag v-if="!record.corrent">错误</a-tag>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-row>
    </a-card>
  </a-spin>

  <EmployeeTableSelectModal ref="selectEmployeeModal" @selectData="onLineaColse" />

  <a-modal v-model:open="data.uploadModalFlag" title="上传文件" @onCancel="hideUploadModal" @ok="hideUploadModal">
    <FileUpload
      list-type="text"
      :maxUploadSize="1"
      buttonText="点击上传文件"
      :defaultFileList="[]"
      :multiple="true"
      :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
      @change="success"
    />
  </a-modal>
</template>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { smartSentry } from '/src/lib/smart-sentry';
  import { examromApi, examromaApi, examrombApi } from '/src/api/business/exam/examrom-api.js';
  import { paperApi } from '/src/api/business/exam/paper-api.js';

  import { useRouter, useRoute } from 'vue-router';

  import { FILE_FOLDER_TYPE_ENUM } from '/src/constants/support/file-const.js';
  import FileUpload from '/src/components/support/file-upload/index.vue';
  import { columnsa, columnsb } from '/@/views/business/exam/exromData/data.js';

  import EmployeeTableSelectModal from '/@/components/system/employee-table-select-modal/index.vue';

  const route = useRoute();
  const router = useRouter();
  const data = reactive({
    form: {
      docEntry: 0,
      objId: '',
      absId: '',
      approved: false,
      docStatus: 'O',
      edit: false,
      updateBy: '',
      lista: [],
      listb: [],
    },
    queryForm: {},
    options: {
      paper: [],
    },
    radioGroup: null,
    rules: {
      absId: [{ required: true, message: '请选择月期间' }],
      deptId: [{ required: true, message: '请选择部门' }],
      macName: [{ required: true, message: '请输入设备名称' }],
      macAddress: [{ required: true, message: '请输入设备地址' }],
    },
    model: {
      absId: '',
    },
    editableData: {
      nowDate: null,
    },
    visible: {
      approvord: false,
      user: false,
    },
    approvedData: {
      baseEntry: null,
      tabName: null,
    },
    activeKey: '1',
    uploadModalFlag: false,
  });
  const tableLoading = ref(false);
  const formRef = ref(null);
  const selectEmployeeModal = ref(null);

  // 初始化
  function init() {
    if (route.query.type === 'info') {
      data.form.docEntry = route.query.docEntry;
      queryData();
    } else {
      data.form.edit = true;
    }
    paperApi
      .queryPage({
        pageNum: 1,
        pageSize: 500,
      })
      .then((res) => {
        data.options.paper = res.data.list;
      });
  }

  // 更多操作
  function more({ key }) {
    // 审核处理函数
    if (key === 'a') {
      data.form.docStatus = 'C';
      tableLoading.value = true;
      examromApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'b') {
      data.form.docStatus = 'O';
      tableLoading.value = true;
      examromApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    }
  }

  // 增删改查
  function add() {
    data.form.objId = 78;
    data.form.objName = '日历';
    data.form.docStatus = 'O';
    data.form.approved = false;
    data.form.absId = null;
    data.form.deptId = null;
    data.form.deptName = null;
    data.form.remark = null;
    data.form.edit = true;
    data.form.lista = [];
    router.push({ path: '/exam/exroma', query: { type: 'new', docEntry: null } });
  }

  function save() {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.docEntry) {
          examromApi
            .update(data.form)
            .then((res) => {
              queryData(data.form.docEntry);
              message.success('修改成功！');
            })
            .catch((err) => {
              tableLoading.value = false;
            });
        } else {
          examromApi.add(data.form).then((res) => {
            data.form.docEntry = res.data;
            message.success('保存成功！');
            router.push({ path: '/exam/exroma', query: { type: 'info', docEntry: res.data } });
            queryData(res.data);
          });
        }
      })
      .catch((err) => {
        message.error('页面校验失败！');
      });
  }

  function edit() {
    data.form.edit = true;
    data.form.lista.forEach((item) => {
      item.edit = true;
    });
  }

  function del() {
    Modal.confirm({
      content: `确认删除（${data.form.docEntry}）`,
      onOk() {
        examromApi.delete(data.form.docEntry).then((res) => {
          message.success('删除成功！');
          router.push({ path: '/exam/exrom' });
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  async function queryData() {
    tableLoading.value = true;
    formRef.value.resetFields();
    try {
      let queryResult = await examromApi.info(data.form.docEntry);

      data.form = queryResult.data;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
      message.success('查询成功！');
    }
  }

  function refresh() {
    queryData();
  }

  function back() {
    router.push({ path: '/exam/exrom' });
  }

  function hideUploadModal(item) {
    data.uploadModalFlag = false;
  }

  function success(item) {
    data.form.thumbnail = item[0].fileUrl;
  }

  function change(item, { key }) {
    data.form.paperName = key;
  }

  // 审核------------------------------------------------------------------------------------------------
  function approved() {
    data.approvedData.baseEntry = data.form.docEntry;
    data.approvedData.tabName = data.form.objName;
    data.visible.approvord = true;
  }

  function onclose() {
    data.visible.approvord = false;
    queryData();
  }

  // 行-------------------------------------------------a----------------------------------------------------

  function handleReset() {
    queryData();
  }

  function handleSearch(it) {
    data.form.lista = data.form.lista.filter((item) => {
      return item.userName.includes(it);
    });
  }

  function lineaEdit(it) {
    it.lineStatus = 'O';
    it.score = 0;
    examromaApi
      .update(it)
      .then((res) => {
        message.success('重置成功！');
      })
      .catch((err) => {});
  }

  function lineaAdd() {
    const lista = data.form.lista.map((item) => {
      return item.userId;
    });
    selectEmployeeModal.value.showModal(lista);
  }

  function onLineaColse(item) {

    tableLoading.value = true
    examromaApi.batchAdd(data.form.docEntry, item).finally(() => {
      tableLoading.value = false;
      queryData()
    })
  }

  function lineaDel(item) {}

  //--------------------------------------------b-------------------------------------------

  function linebAllOpen() {
    tableLoading.value = true;
    examromApi
      .openAll(data.form.docEntry)
      .then((res) => {
        tableLoading.value = false;
        queryData();
      })
      .catch((err) => {
        tableLoading.value = false;
      });
  }

  function linebAllDel() {
    tableLoading.value = true;
    examromaApi.delete(data.form.docEntry).then((res) => {
      tableLoading.value = false;
      queryData();
    });
    examrombApi.delete(data.form.docEntry).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  }

  function onLinebColse(item) {
    data.visible.user = false;
  }

  onMounted(init);
</script>
